<?php
class Wmp_Model_AclrightsTable extends Zend_Db_Table_Abstract
{
    protected $_name = 'aclrights';
    protected $_primary = array('actionid','role');
    
    public function getRolesByAction($actionid)
    {
		$select = $this->select()
                      	->where('actionid = ?', $actionid);
                      	
        return $this->fetchAll($select);
    }
    
    //OPTIMIZEME : optimiser la requette, et la fonction
    //ATTENTION : injection mysql, sécuriser le where par un $db->quote...
    public function getActionsByRole($role,$module='all')
    {
    	$actions = new Wmp_Model_ActionparamsTable();
    	
    	if($module!='all')
    		$actions = $actions->getActions($module);
    	else
    		$actions = $actions->fetchAll();
    	
    	$result = array();
    	foreach ($actions as $action){
    		$registredRoles = $this->getRolesByAction($action->id);

    		$privilege="parent";
    		
    		foreach ($registredRoles as $currentrole) {
    			if($currentrole->role==$role) {
    				$privilege = $currentrole->privilege;
    				break;
    			}
    		}
    		$result[] = array(	'actionid'=>$action->id,
    							'action'=>$action->controller.':'.$action->action,
    							'module'=>$action->module,
    							'description'=>$action->description,
    							'privilege'=>$privilege
    							);
    	}
    	
    	return $result; 
    }
    
    public function existPrivilege($actionid,$role)
    {
    	return $this->find($actionid,$role)->current();
    }
    
    public function setPrivilege($actionid,$role,$privilege)
    {
    	$registredroles = new Wmp_Model_AclRolesTable();
    	$isRoleDefined = $registredroles->find($role)->current();
    	if(!$isRoleDefined) return;
    	
    	//if($this->existPrivilege($actionid,$role)) return ;
    	try {
    		$this->insert(array('actionid'  => $actionid,
	    					'role' => $role,
	    				    'privilege' => $privilege));
    	}
    	catch(EXCEPTION $e){
    		try {
    			$existPrivilege = $this->existPrivilege($actionid,$role);
    			$existPrivilege->privilege = $privilege;
    			$existPrivilege->save();
    		}
    		catch(EXCEPTION $e) {
    			
    		}
    	}
    }
    
    public function deletePrivilege($actionid,$role,$privilege)
    {
    	
    }
}